package com.sy.vedio.controller;

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.util.Date;
import java.util.UUID;

import com.sy.enums.VideoStatusEnum;
import com.sy.utils.FetchVideoCover;
import com.sy.utils.MergeVideoMp3;
import com.sy.utils.Result;
import com.sy.utils.page.PagedResult;
import com.sy.vedio.pojo.Bgm;
import com.sy.vedio.pojo.Comments;
import com.sy.vedio.pojo.Videos;
import com.sy.vedio.service.BgmService;
import com.sy.vedio.service.VideoService;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;


import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;


@RestController
@RequestMapping("/video")
public class VideoController extends BasicController {
	
	@Autowired
	private BgmService bgmService;

	@Autowired
	private VideoService videoService;


	/**
	 * 上传视频
	 * @param userId
	 * @param bgmId
	 * @param videoSeconds
	 * @param videoWidth
	 * @param videoHeight
	 * @param desc
	 * @param file
	 * @return
	 * @throws Exception
	 */
	@PostMapping(value="/upload", headers="content-type=multipart/form-data")
	public Result upload(String userId,
						 String bgmId,
						 double videoSeconds,
						 int videoWidth,
						 int videoHeight,
						 String desc,
						 MultipartFile file) throws Exception {

		if (StringUtils.isBlank(userId)) {
			return Result.errorMsg("用户id不能为空...");
		}

		// 文件保存的命名空间
//		String fileSpace = "D:/小项目/vedio-mini-program/vedio-background-dev/vedio-background-dev-mini-api/video_dev";
		// 保存到数据库中的相对路径
		String uploadPathDB = "/" + userId + "/video";
		String coverPathDB = "/" + userId + "/video";

		FileOutputStream fileOutputStream = null;
		InputStream inputStream = null;
		// 文件上传的最终保存路径
		String finalVideoPath = "";
		try {
			if (file != null) {

				String fileName = file.getOriginalFilename();
				String arrayFilenameItem[] = fileName.split("\\.");
				String fileNamePrefix = "";
				for (int i = 0; i < arrayFilenameItem.length - 1; i++) {
					fileNamePrefix += arrayFilenameItem[i];
				}

				if (StringUtils.isNotBlank(fileName)) {

					finalVideoPath = FILE_SPACE + uploadPathDB + "/" + fileName;
					// 设置数据库保存的路径
					uploadPathDB += ("/" + fileName);
					coverPathDB = coverPathDB + "/" + fileNamePrefix + ".jpg";

					File outFile = new File(finalVideoPath);
					if (outFile.getParentFile() != null || !outFile.getParentFile().isDirectory()) {
						// 创建父文件夹
						outFile.getParentFile().mkdirs();
					}

					fileOutputStream = new FileOutputStream(outFile);
					inputStream = file.getInputStream();
					IOUtils.copy(inputStream, fileOutputStream);
				}

			} else {
				return Result.errorMsg("上传出错...");
			}
		} catch (Exception e) {
			e.printStackTrace();
			return Result.errorMsg("上传出错...");
		} finally {
			if (fileOutputStream != null) {
				fileOutputStream.flush();
				fileOutputStream.close();
			}
		}

		// 判断bgmId是否为空，如果不为空，
		// 那就查询bgm的信息，并且合并视频，生产新的视频
		if (StringUtils.isNotBlank(bgmId)) {
			Bgm bgm = bgmService.queryBgmById(bgmId);
			String mp3InputPath = FILE_SPACE + bgm.getPath();

			MergeVideoMp3 tool = new MergeVideoMp3(FFMPEG_EXE);
			String videoInputPath = finalVideoPath;

			String videoOutputName = UUID.randomUUID().toString() + ".mp4";
			uploadPathDB = "/" + userId + "/video" + "/" + videoOutputName;
			finalVideoPath = FILE_SPACE + uploadPathDB;
			tool.convertor(videoInputPath, mp3InputPath, videoSeconds, finalVideoPath);
		}
		System.out.println("uploadPathDB=" + uploadPathDB);
		System.out.println("finalVideoPath=" + finalVideoPath);

		// 对视频截图（由前端微信截图转到后端截图）
		// 电脑端选择图片时小程序会返回tmpCoverUrl参数，但手机使用时却没有，所以要在后端
		// 用工具截图
		FetchVideoCover fetchVideoCover = new FetchVideoCover(FFMPEG_EXE);
		fetchVideoCover.getCover(finalVideoPath, FILE_SPACE + coverPathDB);

		// 保存视频信息到数据库
		Videos video = new Videos();
		video.setAudioId(bgmId);
		video.setUserId(userId);
		video.setVideoSeconds((float)videoSeconds);
		video.setVideoHeight(videoHeight);
		video.setVideoWidth(videoWidth);
		video.setVideoDesc(desc);
		video.setVideoPath(uploadPathDB);
		video.setCoverPath(coverPathDB);
		video.setStatus(VideoStatusEnum.SUCCESS.value);
		video.setCreateTime(new Date());

		String videoId = videoService.saveVideo(video);


		return Result.ok(video);

	}


	/**
	 * 上传视频封面
	 * 		视频封面和视频将被放在同个目录下
	 * @param userId
	 * @param videoId
	 * @param file
	 * @return
	 * @throws Exception
	 */
	@PostMapping(value="/uploadCover", headers="content-type=multipart/form-data")
	public Result uploadCover(String userId,
							  String videoId,
							  MultipartFile file) throws Exception {

		if (StringUtils.isBlank(videoId) || StringUtils.isBlank(userId)) {
			return Result.errorMsg("视频主键id和用户id不能为空...");
		}


		// 保存到数据库中的相对路径
		String uploadPathDB = "/" + userId + "/video";

		FileOutputStream fileOutputStream = null;
		InputStream inputStream = null;
		// 文件上传的最终保存路径
		String finalCoverPath = "";
		try {
			if (file != null) {

				String fileName = file.getOriginalFilename();
				if (StringUtils.isNotBlank(fileName)) {

					finalCoverPath = FILE_SPACE + uploadPathDB + "/" + fileName;
					// 设置数据库保存的路径
					uploadPathDB += ("/" + fileName);

					File outFile = new File(finalCoverPath);
					if (outFile.getParentFile() != null || !outFile.getParentFile().isDirectory()) {
						// 创建父文件夹
						outFile.getParentFile().mkdirs();
					}

					fileOutputStream = new FileOutputStream(outFile);
					inputStream = file.getInputStream();
					IOUtils.copy(inputStream, fileOutputStream);
				}

			} else {
				return Result.errorMsg("上传出错...");
			}
		} catch (Exception e) {
			e.printStackTrace();
			return Result.errorMsg("上传出错...");
		} finally {
			if (fileOutputStream != null) {
				fileOutputStream.flush();
				fileOutputStream.close();
			}
		}

		videoService.updateVideo(videoId, uploadPathDB);

		return Result.ok();
	}


	/**
	 * 分页查询所以视频信息
	 * @param page
	 * @return
	 */
	@PostMapping("/showAll")
	public Result showAll(@RequestBody Videos video,
						  Integer isSaveRecord,
						  Integer page,
						  Integer pageSize) {
		if (page == null) {
			page = 1;
		}

		if (pageSize == null) {
			pageSize = PAGE_SIZE;
		}

		PagedResult allVideos = videoService.getAllVideos(video, isSaveRecord, page, pageSize);

		return Result.ok(allVideos);
	}


	/**
	 * 显示热搜关键词
	 * @return
	 * @throws Exception
	 */
	@PostMapping(value="/hot")
	public Result hot() throws Exception {
		return Result.ok(videoService.getHotwords());
	}

	/**
	 * 点赞
	 * @param userId
	 * @param videoId
	 * @param videoCreaterId
	 * @return
	 * @throws Exception
	 */
	@PostMapping(value="/userLike")
	public Result userLike(String userId, String videoId, String videoCreaterId)
			throws Exception {
		videoService.userLikeVideo(userId, videoId, videoCreaterId);
		return Result.ok();
	}

	/**
	 * 不喜欢
	 * @param userId
	 * @param videoId
	 * @param videoCreaterId
	 * @return
	 * @throws Exception
	 */
	@PostMapping(value="/userUnLike")
	public Result userUnLike(String userId, String videoId, String videoCreaterId) throws Exception {
		videoService.userUnLikeVideo(userId, videoId, videoCreaterId);
		return Result.ok();
	}


	/**
	 * 我收藏(点赞)过的视频列表
	 * @param userId
	 * @param page
	 * @param pageSize
	 * @return
	 * @throws Exception
	 */
	@PostMapping("/showMyLike")
	public Result showMyLike(String userId, Integer page, Integer pageSize) throws Exception {

		if (StringUtils.isBlank(userId)) {
			return Result.ok();
		}

		if (page == null) {
			page = 1;
		}

		if (pageSize == null) {
			pageSize = 6;
		}

		PagedResult videosList = videoService.queryMyLikeVideos(userId, page, pageSize);

		return Result.ok(videosList);
	}


	/**
	 * 我关注的人发的视频
	 * @param userId
	 * @param page
	 * @return
	 * @throws Exception
	 */
	@PostMapping("/showMyFollow")
	public Result showMyFollow(String userId, Integer page) throws Exception {

		if (StringUtils.isBlank(userId)) {
			return Result.ok();
		}

		if (page == null) {
			page = 1;
		}

		int pageSize = 6;

		PagedResult videosList = videoService.queryMyFollowVideos(userId, page, pageSize);

		return Result.ok(videosList);
	}


	@PostMapping("/saveComment")
	public Result saveComment(@RequestBody Comments comment,
									   String fatherCommentId, String toUserId) throws Exception {

		comment.setFatherCommentId(fatherCommentId);
		comment.setToUserId(toUserId);

		videoService.saveComment(comment);
		return Result.ok();
	}

	@PostMapping("/getVideoComments")
	public Result getVideoComments(String videoId, Integer page, Integer pageSize) throws Exception {

		if (StringUtils.isBlank(videoId)) {
			return Result.ok();
		}

		// 分页查询视频列表，时间顺序倒序排序
		if (page == null) {
			page = 1;
		}

		if (pageSize == null) {
			pageSize = 10;
		}

		PagedResult list = videoService.getAllComments(videoId, page, pageSize);

		return Result.ok(list);
	}

}
